<template>
  <div>
    <n-grid class="mt-4" cols="1 s:1 m:1 l:3 xl:3 2xl:3" responsive="screen" :x-gap="12">
      <n-gi span="1">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-dropdown trigger="hover" @select="selectAddMenu" :options="addMenuOptions">
                <n-button type="info" ghost icon-placement="right">
                  添加菜单
                  <template #icon>
                    <div class="flex items-center">
                      <n-icon size="14">
                        <DownOutlined />
                      </n-icon>
                    </div>
                  </template>
                </n-button>
              </n-dropdown>
              <n-button type="info" ghost icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <AlignLeftOutlined />
                    </n-icon>
                  </div>
                </template>
              </n-button>
            </n-space>
          </template>
          <div class="w-full menu">
            <n-input type="input" v-model:value="pattern" placeholder="输入菜单名称搜索">
              <template #suffix>
                <n-icon size="18" class="cursor-pointer">
                  <SearchOutlined />
                </n-icon>
              </template>
            </n-input>
            <div class="py-3 menu-list">
              <template v-if="loading">
                <div class="flex items-center justify-center py-4">
                  <n-spin size="medium" />
                </div>
              </template>
              <template v-else>
                <n-tree
                  block-line
                  cascade
                  key-field="menuKey"
                  label-field="menuName"
                  :virtual-scroll="true"
                  :pattern="pattern"
                  :data="treeData"
                  :expandedKeys="expandedKeys"
                  style="max-height: 650px; overflow: hidden"
                  @update:selected-keys="selectedTree"
                  @update:expanded-keys="onExpandedKeys"
                />
              </template>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi span="2">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-icon size="18">
                <FormOutlined />
              </n-icon>
              <span>编辑菜单{{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
            </n-space>
          </template>
          <n-alert type="info" closable> 从菜单列表选择一项后，进行编辑</n-alert>
          <n-form
            :model="formParams"
            :rules="rules"
            ref="formRef"
            label-placement="left"
            :label-width="100"
            v-if="isEditMenu"
            class="py-4"
          >
            <n-form-item label="菜单名称" path="menuName">
              <n-input placeholder="请输入菜单名称" v-model:value="formParams.menuName" />
            </n-form-item>
            <n-form-item label="菜单键" path="menuKey">
              <n-input placeholder="请输入菜单键" v-model:value="formParams.menuKey" />
            </n-form-item>
            <n-form-item label="父菜单" path="parentId">
              <n-tree-select
                :options="options"
                key-field="id"
                label-field="menuName"
                :default-expanded-keys="[formParams.parentId]"
                :default-value="formParams.parentId"
                v-model:value="formParams.parentId"
              />
            </n-form-item>
            <n-form-item label="排序" path="sort">
              <n-input-number
                v-model:value="formParams.sort"
                placeholder="菜单序号"
                :min="1"
              />
            </n-form-item>
            <n-form-item path="auth" style="margin-left: 100px">
              <n-space>
                <n-button type="primary" :loading="subLoading" @click="formSubmit">保存修改</n-button>
                <n-button @click="handleReset">重置</n-button>
                <n-button @click="handleDel">删除</n-button>
              </n-space>
            </n-form-item>
          </n-form>
        </n-card>
      </n-gi>
    </n-grid>
    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :parent-id="formParams.id"
      @handlerInit="init"
    />
  </div>
</template>
<script lang="ts" setup>
import { ref, unref, reactive, onMounted, computed } from 'vue';
import { useDialog, useMessage } from 'naive-ui';
// @ts-ignore
import { DownOutlined, AlignLeftOutlined, SearchOutlined, FormOutlined } from '@vicons/antd';
import { getMenuTreeList, updateMenu, deleteMenu, getMenuList } from '@/api/authority/menu';
import { getTreeItem } from '@/utils';
import CreateDrawer from './CreateDrawer.vue';

const rules = {
  menuName: {
    required: true,
    message: '请输入菜单名称',
    trigger: 'blur',
  },
  menuKey: {
    required: true,
    message: '请输入菜单键',
    trigger: 'blur',
  },
  parentId: {
    required: true,
    validator (rule, value: string) {
      if (!value) {
        return new Error('请选择菜单关联父菜单')
      }
      return true
    },
    trigger: 'blur',
  },
  sort: {
    required: true,
    validator (rule, value: string) {
      if (!value) {
        return new Error('请输入菜单序号')
      } else if (!/^\d*$/.test(value)) {
        return new Error('序号应该为整数')
      }
      return true
    },
    trigger: 'blur',
  },
};

const formRef: any = ref(null);
const createDrawerRef = ref();
const message = useMessage();
const dialog = useDialog();

let treeItemKey = ref([]);

let expandedKeys = ref([]);

const treeData = ref([]);
const originMenuData = ref([])

const loading = ref(true);
const subLoading = ref(false);
const isEditMenu = ref(false);
const treeItemTitle = ref('');
const pattern = ref('');
const drawerTitle = ref('');

const isAddSon = computed(() => {
  return !treeItemKey.value.length;
});

const addMenuOptions = ref([
  {
    label: '添加顶级菜单',
    key: 'home',
    disabled: false,
  },
  {
    label: '添加子菜单',
    key: 'son',
    disabled: isAddSon,
  },
]);

const formParams = reactive({
  id: -1,
  menuName: '',
  menuKey: '',
  parentId: -1,
  sort: 1,
});

function selectAddMenu(key: string) {
  drawerTitle.value = key === 'home' ? '添加顶栏菜单' : `添加子菜单：${treeItemTitle.value}`;
  openCreateDrawer();
}

function openCreateDrawer() {
  const { openDrawer } = createDrawerRef.value;
  openDrawer();
}

function selectedTree(keys) {
  if (keys.length) {
    const treeItem = getTreeItem(unref(treeData), keys[0]);
    treeItemKey.value = keys;
    treeItemTitle.value = treeItem.menuName;
    Object.assign(formParams, treeItem);
    options.value = [{
      id: -1,
      menuName: '顶级菜单',
      menuKey: 'menu',
      parentId: -1,
      children: Object.assign([], unref(treeData))
    }]
    formParams.parentId = getPreMenuId(treeItem.id)
    isEditMenu.value = true;
  } else {
    formParams.id = -1;
    isEditMenu.value = false;
    treeItemKey.value = [];
    treeItemTitle.value = '';
  }
}

const options = ref<any[]>([])

function handleDel() {
  dialog.info({
    title: '提示',
    content: `您确定想删除此权限吗?`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      deleteMenu(formParams.id)
        .then(() => init())
        .catch(() => dialog.destroyAll())
    },
    onNegativeClick: () => { },
  });
}

function handleReset() {
  const treeItem = getTreeItem(unref(treeData), treeItemKey.value[0]);
  Object.assign(formParams, treeItem);
}

function formSubmit() {
  formRef.value.validate(async (errors: boolean) => {
    if (!errors) {
      await updateMenu(formParams.id, {
        menuName: formParams.menuName,
        menuKey: formParams.menuKey,
        parentId: formParams.parentId,
        sort: formParams.sort
      })
      await init()
    } else {
      message.error('请填写完整信息');
    }
  });
}

function packHandle() {
  if (expandedKeys.value.length) {
    expandedKeys.value = [];
  } else {
    expandedKeys.value = unref(treeData).map((item: any) => item.menuKey as string) as [];
  }
}

const getPreMenuId = (currentId) => {
  let data = unref(originMenuData);
  let currentData;
  for (let item of data) {
    // @ts-ignore
    if (item.id === currentId) {
      currentData = item;
      break;
    }
  }
  for (let item of data) {
    // @ts-ignore
    if (item.id === currentData?.parentId) {
      return currentData.parentId;
    }
  }
  return -1;
}

const init = async () => {
  const { initOptions } = createDrawerRef.value;
  const treeMenuList = await getMenuTreeList();
  initOptions(treeMenuList)
  originMenuData.value = await getMenuList();
  const keys = treeMenuList.map((item) => item.menuKey);
  Object.assign(formParams, keys);
  treeData.value = treeMenuList;
  loading.value = false;
}

onMounted(async () => {
  await init()
});

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}
</script>
